#!/bin/sh -x
#
# This runs as a cronjob from /etc/cron.d/atnf-web on Sunday morning 1am
#
# It updates the index links for CA and Mopra schedules so it starts up on
# the current page.
# The file "do_not_update_symlink" is used to skip every other week.
# If it exists we remove it and exit.
# On the next run (next week) it will not exist and we update the symlink
# to the index file.
#
# $Source: /var/www/vhosts/www.narrabri.atnf.csiro.au/htdocs/observing/schedules/RCS/updateLink.sh,v $
# $Id: updateLink.sh,v 1.2 2011/04/04 02:37:30 root Exp $
#
PATH=/usr/bin:/bin; export PATH; unalias -a

# Functions
Fail () {
    while test $# -gt 0 ; do echo $1; shift; done; exit 1;
} # Fail

Update () {
    # expects one argument - the prefix for the telescope
    case "$1" in
      CA | MP ) prefix="$1"
      ;;
      *)        Fail "$0:Update() - unexpected argument '$1'"
      ;;
    esac
    
    # compute name of symlink, which should already exist
    link="${prefix}index.html"
    test -e "$link" || Fail "$0: '$link' doesn't exist"
    test -h "$link" || Fail "$0: '$link' is not a symbolic link"

    # pull out the link target
    target=`ls -l "$link" | sed -e 's/.*> //'`
    # warn if target file does not exist
    test -f "$target" || echo "$0: warning- current link target ($target) does not exist"

    # compute the next file to point to
    num=`echo $target | sed -e 's/'"$prefix"'0//' -e 's/.html//'`
    next_num=`expr 1 + $num`
    # format number correctly - two digits, zero-padded
    next_num=`echo $next_num |awk '{printf "%02d",$1}'`
    # final filename has the form PF0nn.html
    next_target=`echo $target | sed -e 's/'"${prefix}0${num}"'/'"${prefix}0${next_num}"'/'`

    # update the link
    test -f "$next_target" || Fail "$0:Update() - next file ($next_target) is missing?"
    test -e "$link" && rm -f "$link"
    ln -s "$next_target" "$link"

} # Update

FLAGFILE="do_not_update_symlink"

TOP="/var/www/vhosts/www.narrabri.atnf.csiro.au/htdocs/observing/schedules"
current="$TOP/current"
#test -d "$current" || Fail "$0: can't find directory '$current'"
#test -w "$current" || Fail "$0: No write permission for '$current'"

cd "$current"

# skip every other week
# Each page of the schedule shows two weeks of observing slots.
# If the current week is the first week of the fortnight shown in the
# schedule page, we do not want to update the symlink, we want to exit now.
# If the current week is the second week of the fortnight, we want to
# update the symlink to point to the next fortnight and set the flag file.
if test -f "$FLAGFILE" ; then
  rm -f "$FLAGFILE"
  exit
fi

touch "$FLAGFILE"

# update current index file for CA and MP
Update CA
Update MP

